package com.rjt.common.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**  
* @comment
* @author renjiangtao 
* @date 2018年8月12日  
* @version 1.0  
*/
public class HttpUtils {
    /**
    * 发送http POST请求
    *
    * @param
    * @return 远程响应结果
    */
   public static String sendPost(String u, String json) {
       StringBuffer sbf = new StringBuffer();
       try {
           URL url = new URL(u);
           HttpURLConnection connection = (HttpURLConnection) url.openConnection();
           connection.setDoInput(true);
           connection.setDoOutput(true);
           connection.setRequestMethod("POST");
           connection.setUseCaches(false);
           connection.setInstanceFollowRedirects(true);
           connection.addRequestProperty("role", "Admin");
           connection.addRequestProperty("Content-Type", "application/json");
           connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
           connection.connect();
           DataOutputStream out = new DataOutputStream(connection.getOutputStream());
           if (!"".equals(json)) {
               out.writeBytes(json);
           }
           out.flush();
           out.close();

           BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
           String lines;
           while ((lines = reader.readLine()) != null) {
               lines = new String(lines.getBytes(), "utf-8");
               sbf.append(lines);
           }
           System.out.println(sbf);
           reader.close();
           // 断开连接
           connection.disconnect();
       } catch (MalformedURLException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       } catch (IOException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }
       return sbf.toString();
   }
}
